import {WebUtils} from './webUtils.js';
import {TableOperation} from './tableOperation.js';
import {Page} from './page.js';


function doDelete(event) {
    let list = document.querySelectorAll(".cbxSelect");
    let parameter = "";
    if (window.confirm("你确定要进行删除操作吗？")) {
        [...list].filter(element => element.checked).forEach((element) => {
            if (parameter == '') {
                parameter += element.dataset.oid;
            } else {
                parameter += ',';
                parameter += element.dataset.oid;
            }
        });
        if (parameter == '') {
            alert("请选择要删除的数据行！");
            return;
        }
        window.location.href="user.servlet?param=delete&ids="+parameter;
    }
}

function doAdd() {
    document.getElementById("userTable").hidden = true;
    document.getElementById("userOperation").hidden = false;
    document.getElementById("operationMsg").innerHTML = "->&nbsp;新增用户";
}

function doUpdate() {}

function updateInit(response){
	let json=response.data;
	if(json.result=="ok"){
        document.getElementById("userTable").hidden = true;
        document.getElementById("userOperation").hidden = false;
        document.getElementById("operationMsg").innerHTML = "->&nbsp;修改用户";     
        document.getElementById("userId").value=json.userAndUserDetail.id;
        //document.getElementById("userDetailId").value=json.userAndUserDetail.userDetailId;
        document.getElementById("userName").value=json.userAndUserDetail.userName;
        document.getElementById("nickName").value=json.userAndUserDetail.nickName;
        document.getElementById("password").value=json.userAndUserDetail.password;
        document.getElementById("email").value=json.userAndUserDetail.email;
        document.getElementById("phone").value=json.userAndUserDetail.phone;
        let strDate=new WebUtils().getDate(json.userAndUserDetail.birthday);
        document.getElementById("birthday").value=strDate;
        if(json.userAndUserDetail.sex==1){
        	document.getElementById("man").checked=true;
        }else if(json.userAndUserDetail.sex==2){
        	document.getElementById("woman").checked=true;
        }
        let hobby=document.getElementById("hobbyInsertPoint");
        hobby.length=0;
        json.hobbies.forEach(element=>{
        	let input=document.createElement("input");
        	input.type="checkbox";
        	input.value=element.code;
        	input.name="hobbies";
        	if(element.checked){
        		input.checked=true;
        	}
        	hobby.appendChild(input);
        	hobby.appendChild(document.createTextNode(element.name))
        });
        let province=document.getElementById("province");
        province.length=0;
        let currentProvinceCode=json.userAndUserDetail.nativePlace_code.substring(0,2);
        json.provinces.forEach(element=>{
        	let option=document.createElement("option");
        	option.value=element.code;
        	option.innerHTML=element.name;
        	if(element.code==currentProvinceCode){
        		option.selected=true;
        	}
        	province.appendChild(option);
        });
        let city=document.getElementById("city");
        city.length=0;
        json.cities.filter(element=>currentProvinceCode==element.code.substring(0,2)).forEach(element=>{
        	let option=document.createElement("option");
        	option.value=element.code;
        	option.innerHTML=element.name;
        	if(element.code==json.userAndUserDetail.nativePlace_code){
        		option.selected=true;
        	}
        	city.appendChild(option);            	
        });
	}else{
		alert("数据查询错误！");
	}
}

function updateSearch() {
    let list = document.querySelectorAll(".cbxSelect");
    let parameter = "";
    let count = 0;
    let fList = [...list].filter(element => element.checked);
    if (fList.length > 1) {
        alert("一只能修改一行数据！");
    } else if (fList.length == 0) {
        alert("请选择要修改的数据行！");
    } else {
        parameter = fList[0].dataset.oid;
        axios.get("user.servlet?param=update&id="+parameter)
        .then(response=>{
        	updateInit(response);
        })
        .catch(error=>{
        	console.log(error);
        });
    }
}
function provinceChange(){
	let currentProvinceCode=document.getElementById("province").value;
	axios.get("np.servlet?param=cities&provinceCode="+currentProvinceCode)
	.then(response=>{
		let city=document.getElementById("city");
		city.length=0;
        let provinceValue = document.getElementById("province").value;
        let json = response.data;
        if (json.result == "ok") {
            json.list.forEach((element) => {
                let option = document.createElement("option");
                [option.value, option.innerHTML] = [element.code, element.name];
                city.appendChild(option);
            });
        }
	}).catch(error=>console.log(error));
}

function roleInit(response){
	console.log(response.data);
	document.getElementById("userTable").hidden = true;
	document.getElementById("roleOperation").hidden=false;
	document.getElementById("operationMsg").innerHTML = "->&nbsp;修改用户角色";  
	document.getElementById("userNameInsertPoint").innerHTML=response.data.user.userName+"，昵称："+response.data.user.nickName;
	document.getElementById("roleOperationUserId").value=response.data.user.id;
	let tbody=document.getElementById("roleInsertPoint");
	let list=response.data.list;
	//构造权限选择结构
	let tr=document.createElement("tr");
	tbody.appendChild(tr);
	let count=0;
	list.forEach(role=>{
		let td0=document.createElement("td");
		td0.setAttribute("class","module_level");
		let input0=document.createElement("input");
		input0.type="checkbox";
		input0.value=role.id;
		input0.name="roleId";
		input0.setAttribute("class","normalCheckbox");
		if(role.checked){
			input0.checked=true;
		}
		let span=document.createElement("span");
		span.innerHTML=role.roleName;
		span.setAttribute("class","normal_Text");
		td0.appendChild(input0);
		td0.appendChild(span);
		tr.appendChild(td0);
		count++;
		if(count%4==0){
			tr=document.createElement("tr");
			tbody.appendChild(tr);
		}
	});
}

function searchUser(){
    let list = document.querySelectorAll(".cbxSelect");
    let parameter = "";
    let count = 0;
    let fList = [...list].filter(element => element.checked);
    if (fList.length > 1) {
        alert("一只能修改一行数据！");
    } else if (fList.length == 0) {
        alert("请选择要修改的数据行！");
    } else {
        parameter = fList[0].dataset.oid;
        axios.get("role.servlet?param=search&id="+parameter)
        .then(response=>{
        	roleInit(response);
        })
        .catch(error=>{
        	console.log(error);
        });
    }		
}
function updateRole(){
	
}
function init(){
	let tableOperation = new TableOperation();
	document.getElementById("norTableTbody").addEventListener("click", tableOperation.selectRow, false); //选择行操作
	document.querySelectorAll(".cbxSelect").forEach((element) => {
		tableOperation.toggleInput(element);
	});
	document.getElementById("all").addEventListener("change", tableOperation.allSelect, false);
	//CRUD delete
	document.getElementById("btnDelete").addEventListener("click", doDelete, false);
	//CRUD add
	//document.getElementById("btnAdd").addEventListener("click", doAdd, false);
	//CRUD add return
	document.getElementById("return").addEventListener("click", () => {
	    document.getElementById("userTable").hidden = false;
	    document.getElementById("userOperation").hidden = true;
	    document.getElementById("operationMsg").innerHTML = "";
	}, false);
	//CRUD update
	document.getElementById("btnUpdate").addEventListener("click", updateSearch, false);
	document.getElementById("province").addEventListener("change",provinceChange,false);
	//role update search
	document.getElementById("btnRoleUpdate").addEventListener("click",searchUser,false);
	//role update
	document.getElementById("roleOperationAdd").addEventListener("click",updateRole,false);
	//page
	let page=new Page();
	let url="user.servlet?param=init";
	document.getElementById("pageGroup").addEventListener("click",event=>page.pageOpation(event,url),false);
	document.getElementById("jumpPage").addEventListener("change",event=>page.pageOpation(event,url),false)
}
window.addEventListener("load",init,false);